package com.mall.product.web;

import com.mall.product.entity.CategoryEntity;
import com.mall.product.service.CategoryService;
import com.mall.product.vo.Category2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    CategoryService categoryService;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //todo 查出所有的1级分类
        List<CategoryEntity> categoryEntities =  categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Category2Vo>> getCatalogJson(){
        Map<String, List<Category2Vo>> map =  categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //获取锁，只要锁名一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();
         try {
             System.out.println("加锁成功。。。。" + Thread.currentThread().getId());
             Thread.sleep(30000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         } finally {
             System.out.println("释放锁"+ Thread.currentThread().getId());
             lock.unlock();
         }

        return "hello";
    }

}
